//
//  NetWorkViewController.m
//  MVVM+RAC
//
//  Created by bopeng on 16/5/13.
//  Copyright © 2016年 Scott. All rights reserved.
//

#import "NetWorkViewController.h"
#import "NetWorkViewModel.h"
#import "NetWorkModel.h"

@interface NetWorkViewController ()<UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NetWorkViewModel *netWorkViewModel;

@end

@implementation NetWorkViewController

- (NetWorkViewModel *)netWorkViewModel {
    return _netWorkViewModel ? : (_netWorkViewModel = [[NetWorkViewModel alloc] init]);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"网络请求";
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [UIView new];

    
    
    [self requestData];
}

- (void)requestData {
    RACSignal *requestSignal = [self.netWorkViewModel.requestCommand execute:nil];
    // 获取请求的数据
    [requestSignal subscribeNext:^(id x) {
        if (![x isKindOfClass:[NSError class]]) {
            self.netWorkViewModel.modelsArr = x;
            [self.tableView reloadData];
        }
    }];
    
    CGFloat height = self.view.frame.size.height;
    
    [[[RACObserve(self.tableView, contentOffset) map:^id(id value) {
        if (self.tableView.contentOffset.y < -50) {
            return @"1";
        }
        if (self.tableView.contentOffset.y > self.tableView.contentSize.height - height * 1.5 && self.tableView.contentSize.height - height * 1.5 > 0) {
            return @"2";
        }else{
            return @"0";
        }
    }] distinctUntilChanged] subscribeNext:^(id x) {

        if ([x integerValue] == 1) {
            NSLog(@"下拉刷新");
        }else if ([x integerValue] == 2){
            NSLog(@"上拉加载");
        }
    }];
    
}

- (void)loadMoreData {

}

#pragma mark - 
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.netWorkViewModel.modelsArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cellID"];
    }
    
     NetWorkModel *model = self.netWorkViewModel.modelsArr[indexPath.row];
    
    cell.textLabel.text = model.title;
    cell.detailTextLabel.text = model.subtitle;
    
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
